    //
//  SimpleCalculatorViewController.m
//  LecturePad
//
//  Created by kyocooro on 2/17/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "SimpleCalculatorViewController.h"


@implementation SimpleCalculatorViewController

- (NSString *) decodeKeypress: (int)keycode {
	// the keys are arranged as such on the keyboard
	char * keys[6][4] = {
		{ "mc", "m+", "m-", "mr" }, 
		{ "c", "~", "/", "*" }, 
		{ "7", "8", "9", "-" },
		{ "4", "5", "6", "+" },
		{ "1", "2", "3", "=" },
		{ "0", "0", ".", "=" }
	};
	
	// decode keycode
	NSString *key = [[NSString alloc] initWithCString: keys[ (int)(keycode / 10) ][ keycode % 10 ]];
	//NSLog(@"keypress: ==> %@", key);
	return key;
}
- (void) updateDisplay {

	[resultLabel setText:displayString];
}

- (void) setNegative :(unichar)cmd{
	if(cmd	== '~') 
	{
		@try {
			char firstC = [displayString characterAtIndex:0];
			if (firstC == '-') {
				[displayString replaceCharactersInRange:NSMakeRange(0, 1) withString:@""];
			}
			else {
				[displayString insertString:@"-" atIndex:0];
			}
		}
		@catch (NSException * e) {
			
		}
		
	}else [displayString appendFormat: @"%c", cmd];
}

- (void) handleCommand: (NSString *) command {
	//NSLog(@"BasicCalculatorView handleCommand: [%@] display=[%@]", command, display);

	if ([command length] == 1) {
		unichar cmd = [command characterAtIndex: 0];
		if (isdigit(cmd) || (cmd == '.') || cmd	== '~') 
		{
			// reset the display to blank when we hit
			// our first digit of an entry.
			if (resetDisplay == YES) {
				[displayString setString: @""];
			}
			
			[self setNegative:cmd];
			[self updateDisplay];
			
			// if we are mid-digits don't reset the display
			// on the next digit.
			resetDisplay = NO;
			return;
		}
		
		
	}
	
	// Send the collected number (if any) to the controller
	// Don't send the number if they hit two operations
	// in a row, the engine should get them just the order
	// we did.
	if (resetDisplay == NO) {
		[engine sendCommand: displayString];
	}
	
	// Send the collected operator to the controller
	[engine sendCommand: command];
	
	// indicate that what is in the display is a result
	// and a digit-decimal entry should reset it.
	resetDisplay = YES;
	
	// get the result and display it in the view
	[displayString setString: [engine getCurrentResult]];
	[self updateDisplay];
}
- (IBAction)keyPressAction:(UIView *)sender
{
	int keyCode = sender.tag;
	NSString *keyString = [self decodeKeypress:keyCode];
	[self handleCommand:keyString];
}
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        // Custom initialization
		displayString = [[NSMutableString alloc] init];
		engine = [[SimpleCalculatorEngine alloc] init];
		resetDisplay = YES;
    }
    return self;
}

/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
}
*/

- (IBAction)closeAction:(id)sender
{
  if( [self.parentViewController isKindOfClass:[UIPopoverController class]] )
  {
   	[(UIPopoverController*)self.parentViewController dismissPopoverAnimated:YES];
  }
  else {
    [self.parentViewController dismissModalViewControllerAnimated:YES];
  }
}

- (IBAction)copyResult:(id)sender
{
	[[UIPasteboard generalPasteboard] setString:resultLabel.text];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
    return YES;
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}


- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[resultLabel release];
	[displayString release];
	[engine release];
    [super dealloc];
}


@end
